package Test;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TestSpark {
    public static void main(String[] args) {
//        //设置日志，不打印太多日志
//        Logger.getLogger("org").setLevel(Level.OFF);
//        System.setProperty("spark.ui.showConsoleProgress","false");
        // 创建配置对象                                           setMaster设置为本地运行模式
        SparkConf conf = new SparkConf().setAppName("park").setMaster("local");
        // 创建JavaSparkContext对象
        JavaSparkContext sc = new JavaSparkContext(conf);

        // 读数据
        JavaRDD<String> rdd1 = sc.textFile(args[0]);

        // 分词
        JavaRDD<String> rdd2 = rdd1.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String s) throws Exception {
                return Arrays.asList(s.split(" ")).iterator();
            }
        });
        // 计数                             PairFunction<传进来的每一个数据类型,rdd2返回的数据类型,计数>
        JavaPairRDD<String, Integer> rdd3 = rdd2.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String word) throws Exception {
                return new Tuple2<String, Integer>(word, 1);
            }
        });
        // 累加
        JavaPairRDD<String, Integer> rdd4 = rdd3.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer integer, Integer integer2) throws Exception {
                return integer + integer2;
            }
        });

        // 触发计算
        List<Tuple2<String, Integer>> result = rdd4.collect();

        // 打印
        for (Tuple2<String, Integer> r : result){
            System.out.println(r._1 + "\t" + r._2);
        }

        // 释放资源
        sc.stop();

    }
}
